package com.tierstall.client.view.content;

import java.util.ArrayList;
import java.util.Comparator;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.SelectionCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionModel;
import com.tierstall.client.presenter.UserMGMTPresenter;
import com.tierstall.client.view.main.ContentWidget;
import com.tierstall.shared.Logger;
import com.tierstall.shared.Page;
import com.tierstall.shared.UserDTO;
import com.tierstall.shared.UserType;

public class CV_TierMGMT extends ContentWidget {
	public interface Display {
		// Presenter Methods here
		void onAddClicked(String genehmigung, String leiter);
	}

//	private static CV_UserMGMTUiBinder uiBinder = GWT
//			.create(CV_UserMGMTUiBinder.class);

	interface Binder extends UiBinder<Widget, CV_TierMGMT> {
	}

	// Presenter
	private UserMGMTPresenter presenter;

	public void setPresenter(UserMGMTPresenter presenter) {
		this.presenter = presenter;
	}

	// Constructor
	public CV_TierMGMT(CwConstants constants) {
		super(constants.cwCellTableName(), constants.cwCellTableDescription(),
				false, constants.cwCellTablePermission(), constants
						.cwCellTablePageName());
		this.constants = constants;
		// initWidget(onInitialize());
	}

	/**
	 * The constants used in this Content Widget.
	 */
	public static interface CwConstants extends Constants {
		String cwCellTableColumnAddress();

		String cwCellTableColumnCategory();

		String cwCellTableColumnFirstName();

		String cwCellTableColumnLastName();

		String cwCellTableDescription();

		String cwCellTableName();

		UserType cwCellTablePermission();

		Page cwCellTablePageName();
	}

//	/**
//	 * The main CellTable.
//	 */
	@UiField(provided = true) CellTable<UserDTO> cellTable;
//	@UiField CellTable<UserDTO> cellTable;
//
//	/**
//	 * The pager used to change the range of data.
//	 */
	@UiField(provided = true)
	SimplePager pager;
//	@UiField SimplePager pager;

	/**
	 * An instance of the constants.
	 */
	private CwConstants constants;

	/**
	 * Initialize this example.
	 */
	@Override
	public Widget onInitialize() {
		// Create the UiBinder.
		initCellTable(null);
		Binder uiBinder = GWT
				.create(Binder.class);
		if (uiBinder == null)
			Logger.CLIENT_INFO("it is null! :o");
		Widget widget = uiBinder.createAndBindUi(this);
		return widget;
	}

	public CellTable<UserDTO> initCellTable(ArrayList<UserDTO> userList) {
		// Create a CellTable.
		// Set a key provider that provides a unique key for each contact. If
		// key is
		// used to identify contacts when fields (such as the name and address)
		// change.
		cellTable = new CellTable<UserDTO>(UserDTO.KEY_PROVIDER);
		cellTable.setWidth("100%", true);

		// Attach a column sort handler to the ListDataProvider to sort the
		// list.
		ListHandler<UserDTO> sortHandler = new ListHandler<UserDTO>(userList);
		cellTable.addColumnSortHandler(sortHandler);

		// Create a Pager to control the table.
		SimplePager.Resources pagerResources = GWT
				.create(SimplePager.Resources.class);
		pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0,
				true);
		pager.setDisplay(cellTable);

		// Add a selection model so we can select cells.
		final SelectionModel<UserDTO> selectionModel = new MultiSelectionModel<UserDTO>(
				UserDTO.KEY_PROVIDER);
		cellTable.setSelectionModel(selectionModel,
				DefaultSelectionEventManager.<UserDTO> createCheckboxManager());

		// Initialize the columns.
		initTableColumns(selectionModel, sortHandler);

		// Add the CellList to the adapter in the database.
		// CViewShowUsersPresenter.get().addDataDisplay(cellTable);
		// presenter.setCellTable(cellTable);
		return cellTable;
	}

	/**
	 * Add the columns to the table.
	 */
	private void initTableColumns(final SelectionModel<UserDTO> selectionModel,
			ListHandler<UserDTO> sortHandler) {
		// Checkbox column. This table will uses a checkbox column for
		// selection.
		// Alternatively, you can call cellTable.setSelectionEnabled(true) to
		// enable
		// mouse selection.
		Column<UserDTO, Boolean> checkColumn = new Column<UserDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(UserDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};
		cellTable.addColumn(checkColumn,
				SafeHtmlUtils.fromSafeConstant("<br/>"));
		cellTable.setColumnWidth(checkColumn, 40, Unit.PX);

		// First name.
		Column<UserDTO, String> firstNameColumn = new Column<UserDTO, String>(
				new EditTextCell()) {
			@Override
			public String getValue(UserDTO object) {
				return object.getFirstname();
			}
		};
		firstNameColumn.setSortable(true);
		sortHandler.setComparator(firstNameColumn, new Comparator<UserDTO>() {
			public int compare(UserDTO o1, UserDTO o2) {
				return o1.getFirstname().compareTo(o2.getFirstname());
			}
		});
		cellTable.addColumn(firstNameColumn,
				constants.cwCellTableColumnFirstName());
		firstNameColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
			public void update(int index, UserDTO object, String value) {
				// Called when the user changes the value.
				object.setFirstname(value);
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateUser(object);
			}
		});
		cellTable.setColumnWidth(firstNameColumn, 20, Unit.PCT);

		// Last name.
		Column<UserDTO, String> lastNameColumn = new Column<UserDTO, String>(
				new EditTextCell()) {
			@Override
			public String getValue(UserDTO object) {
				return object.getLastname();
			}
		};
		lastNameColumn.setSortable(true);
		sortHandler.setComparator(lastNameColumn, new Comparator<UserDTO>() {
			public int compare(UserDTO o1, UserDTO o2) {
				return o1.getLastname().compareTo(o2.getLastname());
			}
		});
		cellTable.addColumn(lastNameColumn,
				constants.cwCellTableColumnLastName());
		lastNameColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
			public void update(int index, UserDTO object, String value) {
				// Called when the user changes the value.
				object.setLastname(value);
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateUser(object);
			}
		});
		cellTable.setColumnWidth(lastNameColumn, 20, Unit.PCT);

		// Category.
		// final Category[] categories =
		// CViewShowUsersPresenter.get().queryCategories();
		// List<String> categoryNames = new ArrayList<String>();
		// for (Category category : categories) {
		// categoryNames.add(category.getDisplayName());
		// }
		ArrayList<String> userTypes = new ArrayList<String>();
		for (int i = 0; i < UserType.values().length; i++)
			userTypes.add(UserType.values()[i].type());
		SelectionCell categoryCell = new SelectionCell(userTypes);
		Column<UserDTO, String> categoryColumn = new Column<UserDTO, String>(
				categoryCell) {
			@Override
			public String getValue(UserDTO object) {
				return object.getPermission().type();
			}
		};
		cellTable.addColumn(categoryColumn,
				constants.cwCellTableColumnCategory());
		categoryColumn.setFieldUpdater(new FieldUpdater<UserDTO, String>() {
			public void update(int index, UserDTO object, String value) {
				for (UserType category : UserType.values()) {
					if (category.type().equals(value)) {
						object.setPermission(category);
					}
				}
				// CViewShowUsersPresenter.get().refreshDisplays();
				presenter.updateUser(object);
			}
		});
		cellTable.setColumnWidth(categoryColumn, 130, Unit.PX);

		// Address.
		Column<UserDTO, String> addressColumn = new Column<UserDTO, String>(
				new TextCell()) {
			@Override
			public String getValue(UserDTO object) {
				return object.getEmail();
			}
		};
		addressColumn.setSortable(true);
		sortHandler.setComparator(addressColumn, new Comparator<UserDTO>() {
			public int compare(UserDTO o1, UserDTO o2) {
				return o1.getEmail().compareTo(o2.getEmail());
			}
		});
		cellTable
				.addColumn(addressColumn, constants.cwCellTableColumnAddress());
		cellTable.setColumnWidth(addressColumn, 60, Unit.PCT);
	}

	@Override
	protected void asyncOnInitialize(final AsyncCallback<Widget> callback) {
		GWT.runAsync(CV_TierMGMT.class, new RunAsyncCallback() {

			public void onFailure(Throwable caught) {
				callback.onFailure(caught);
			}

			public void onSuccess() {
				callback.onSuccess(onInitialize());
			}
		});

	}

}
